﻿using BJJCZ_BaseDevelop;
using GeneralAPI;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Laser_HandIO
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            LaserIniPath = CINIOperationClass.GetSetting("位置信息", "激光文件位置", "", Ini_SysPath);
            label_打标地址.Text = "打标文件地址：" + LaserIniPath;
            LaserFileName = CINIOperationClass.GetSetting("位置信息", "激光文件名称", "", Ini_SysPath);

            JczLmc.Close();
            JczLmc.Initialize(Application.StartupPath, false);
            OpenLaserType(); DataName = LaserFileName;
            TH_Data刷新();
            TH_IO刷新();
            TH_生产IO信号刷新();
            TH_红光预览刷新();
            Director();

           

            timer1.Enabled = true;
        }

        private void Timer1_Tick(object sender, EventArgs e)
        {
            DateTime dt2 = System.DateTime.Now;
            TimeSpan ts = dt2.Subtract(starttime);
            string SWruntime = "运行时间：" + string.Format("{0} 天{1} 时{2} 分{3} 秒", ts.Days, ts.Hours, ts.Minutes, ts.Seconds);
            status_软件运行时间.Text = SWruntime;

            status_CurTime.Text = "当前时间：" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");

            button_OUT5_脚踏开关.DefaultBack = Card_INputStatus[5] ? Color.Green : Color.DarkRed;

            label_打标耗时.Text = "打标耗时：" + int_打标耗时.ToString() + " ms  ";

            label_生产数据.Text = "生产总计数：" + int_加工总计数.ToString() + "     当前机型加工计数：" + int_当前型号加工数量.ToString();
            if (b_生产中)
            {
                button_启动.Enabled = false;
            }
            else
            {
                button_启动.Enabled = true;
            }
            label_激光文件名称.Text = "激光文件名称：" + LaserFileName;
            label_获取打标文档内容.Text = "打标文档内容：" + LaserContent;
            if (LaserFileName == LaserContent || checkBox_不比对.Checked)
            {
                b_数据比对 = true;
               
            }
            else
            {
                b_数据比对 = false;
            }
            if (b_数据比对)
            {
                label_激光文件名称.ForeColor = Color.Green;
                label_获取打标文档内容.ForeColor = Color.Green;
            }
            else
            {
                label_激光文件名称.ForeColor = Color.Red;
                label_获取打标文档内容.ForeColor = Color.Red;
            }
            if (b_生产中)
            {
                button_machine_statue.Text = "运行中";
                button_machine_statue.ForeColor = Color.Green;
            }
            else
            {
                button_machine_statue.Text = "暂停中";
                button_machine_statue.ForeColor = Color.OrangeRed;
            }
            if (red)
            {
                Button_红光预览.ForeColor = Color.Red;
            }
            else
            {
                Button_红光预览.ForeColor = Color.FromArgb(247, 250, 255);
            }

        }

        #region 接口
        /// <summary>
        /// 激光初始化
        /// </summary>
        public void OpenLaserType()
        {           
            if (File.Exists(LaserIniPath))
            {
                JczLmc.Close();
                JczLmc.Initialize(Application.StartupPath, false);
                int nErr = JczLmc.LoadEzdFile(LaserIniPath);
                try
                {
                    pictureBox_LaserShow.Image = JczLmc.GetCurPreviewImage(pictureBox1.Width, pictureBox1.Height);
                }
                catch (Exception)
                {

                }

                string name1 = Path.GetFileName(LaserIniPath);
                LaserFileName = name1.Substring(0, name1.Length - 3);               

                try
                {
                    int nCount = JczLmc.GetEntityCount();
                    if (nCount == 1)
                    {
                        var name = JczLmc.GetEntityNameByIndex(0);

                        StringBuilder Temp_Name = new StringBuilder("", 255);
                        JczLmc.GetTextByName(name, Temp_Name);
                        LaserContent = Temp_Name.ToString().TrimEnd('\n');
                    }
                    else
                    {
                        LaserContent = "打标文件数据异常，无法识别！";
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show(new Form { TopMost = true }, "打标文档数据获取失败！");

                }

            }
            else
            {
                CGeneralMethods.SaveFormAction("异常信息", "激光初始化未成功！请检查路径下有无激光文件！！");
            }
        }

        /// <summary>
        /// 激光文件列表刷新
        /// </summary>
        public void Director()
        {
            try
            {
                LaserPath = CINIOperationClass.GetSetting("地址", "激光文件地址", "D:\\", Application.StartupPath + "\\Param\\SysIni.ini");
                string[] files = Directory.GetFiles(LaserPath);

                lb_Show_Mes.Items.Clear();
                for (int i = 0; i < files.Length; i++)
                {
                    string temp = Path.GetFileName(files[i]); // 输出文件名
                    temp = temp.Substring(0, temp.Length - 4);
                    if (textBox搜索.Text != "")
                    {
                        if (temp == textBox搜索.Text)
                        {
                            lb_Show_Mes.Items.Insert(0, temp);
                        }
                    }
                    else
                    {
                        if (lb_Show_Mes.Items.Count < 100)
                        {
                            lb_Show_Mes.Items.Insert(0, temp);
                        }
                    }
                }
            }
            catch (Exception er)
            {
                MessageBox.Show(new Form { TopMost = true }, "请配置激光文件目录！" + er.Message);
            }
         
        }

        public void ShowEzCad()
        {
            if (!isShowEzCad)
            {
                isShowEzCad = true;
                new Thread(() => Edit()) { IsBackground = true }.Start();
            }
            else
            {
                MessageBox.Show(new Form { TopMost = true }, "Ezcad2已经在运行");
            }
        }

        private void Edit()
        {
            File.Delete("D:\\temp.ezd");
            File.Move(LaserIniPath, "D:\\temp.ezd");
            File.Delete(LaserIniPath);
          

            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.CreateNoWindow = true;//设不显示窗口
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.FileName = Application.StartupPath + @"\" + "Ezcad2.exe";
            process.StartInfo.Arguments = "D:\\temp.ezd";
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            try
            {
                process.Start();
            }
            catch (System.ComponentModel.Win32Exception we)
            {
                process.Dispose();
                MessageBox.Show(new Form { TopMost = true }, we.Message);
                isShowEzCad = false;
                return;
            }
            process.WaitForExit();
            File.Move("D:\\temp.ezd", LaserIniPath);

            process.Dispose();
            OpenLaserType();
            isShowEzCad = false;
        }

        private void Mark()
        {
            stopwatch_打标耗时.Restart();
            JczLmc.Mark(false);
            stopwatch_打标耗时.Stop();
            int_打标耗时 = stopwatch_打标耗时.ElapsedMilliseconds;
        }


        #endregion

        #region 变量
        public  long int_打标耗时 = 0;
        Stopwatch stopwatch_打标耗时 = new Stopwatch();
        /// <summary>
        /// EzCAD显示中
        /// </summary>
        public bool isShowEzCad = false;
        public bool b_生产中 = false;
        /// <summary>
        /// 软件打开初始时间
        /// </summary>
        DateTime starttime = DateTime.Now;
        /// <summary>
        /// 镭雕文件地址
        /// </summary>
        public static string LaserIniPath = "";
        /// <summary>
        /// 镭雕文件目录
        /// </summary>
        public static string LaserPath = "";
        /// <summary>
        /// 雕刻文件名称
        /// </summary>
        public static string LaserFileName = "";
        /// <summary>
        /// 雕刻文件文字内容
        /// </summary>
        public string LaserContent = "空";
        public bool b_数据比对 = false;
        /// <summary>
        /// 系统所有机型的通用参数
        /// </summary>
        public string Ini_SysPath = Application.StartupPath + "\\Param\\SysIni.ini";
        /// <summary>
        /// 生产日志地址
        /// </summary>
        public string DataPath = "";
        string DataName = "";
        List<string> TypeData = new List<string>();
        /// <summary>
        /// 更新加工计数标志位
        /// </summary>
        public bool b_更新加工计数 = false;
        /// <summary>
        /// 当前型号加工数量
        /// </summary>
        int int_当前型号加工数量 = 0;
        /// <summary>
        /// 激光加工计数
        /// </summary>
        public int int_加工总计数 = 0;
        #endregion

        #region 线程
        public static bool[] Card_INputStatus = new bool[] { false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false };
        public string hex_vavlue = "";
        void TH_IO刷新()
        {
            Task task = Task.Run(() =>
            {
                while (true)
                {
                    #region IO刷新
                    try
                    {
                        ushort uData = 0;
                        int nErr = JczLmc.ReadPort(ref uData);
                        hex_vavlue = uData.ToString();
                        for (int i = 0; i < 16; i++)
                        {
                            int nbit = 1 << i;//目标位值预置为高

                            int nCurBitData = ((int)uData & nbit);//目标值与获取值做与运动，仅保留相同位数据

                            Card_INputStatus[i] = nCurBitData != 0;
                        }
                    }
                    catch (Exception er)
                    {

                    }

                    #endregion
                    Thread.Sleep(100);
                }
            });
        }
        void TH_生产IO信号刷新()
        {
            Task task = Task.Run(() =>
            {
                while (true)
                {
                    #region TH_生产IO信号刷新
                    if (b_生产中)
                    {
                        if (Card_INputStatus[5])
                        {
                            Mark();
                            b_更新加工计数 = true;
                            Thread.Sleep(500);
                        }
                    }
                  
                    #endregion
                    Thread.Sleep(10);
                }
            });
        }
        void TH_红光预览刷新()
        {
            Task task = Task.Run(() =>
            {
                while (true)
                {
                    #region TH_红光预览刷新
                    if (red)
                    {
                        JczLmc.RedMark(); 
                    }                

                    #endregion

                    Thread.Sleep(50);
                }
            });
        }
        void TH_Data刷新()
        {
            Task task = Task.Run(() =>
            {
                while (true)
                {
                    #region Data刷新
                    string strLogFile = "D:\\Data\\生产日志\\" + DateTime.Now.ToString(DateTime.Now.ToString("yyyy年MM月dd日"));
                    DataPath = strLogFile + "\\生产日志.ini";
                    if (!Directory.Exists(strLogFile))
                    {
                        Directory.CreateDirectory(strLogFile);
                    }
                    if (!File.Exists(DataPath))
                    {
                        CINIOperationClass.INIWriteValue(DataPath, "加工计数", "加工总计数", "0");
                        CINIOperationClass.INIWriteValue(DataPath, "不同机型加工计数", LaserContent, "0");
                        string temp = "当前机型为：" + LaserContent + "     当前时间：" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss" + "     此信息为当天第一条信息信息");
                        TypeData.Add(temp);
                    }

                    if (TypeData.Count > 0)
                    {
                        CINIOperationClass.INIWriteValue(DataPath, LaserContent, "时间节点", TypeData[0]);
                        TypeData.RemoveAt(0);
                    }
                    int_加工总计数 = int.Parse(CINIOperationClass.GetSetting("加工计数", "加工总计数", int_加工总计数.ToString(), DataPath));
                    int_当前型号加工数量 = int.Parse(CINIOperationClass.GetSetting("不同机型加工计数", DataName, int_当前型号加工数量.ToString(), DataPath));
                    if (b_更新加工计数)
                    {
                        b_更新加工计数 = false;

                        int_加工总计数= int_加工总计数 + 1;
                        int_当前型号加工数量 = int_当前型号加工数量 + 1;

                        CINIOperationClass.INIWriteValue(DataPath, "加工计数", "加工总计数", int_加工总计数.ToString());
                        CINIOperationClass.INIWriteValue(DataPath, "不同机型加工计数", DataName, int_当前型号加工数量.ToString());
                    }
                    #endregion
                    Thread.Sleep(100);
                }
            });
        }
        #endregion

        #region 菜单栏
        private void Button_ExitComputer_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(new Form { TopMost = true }, "确认关闭计算机？", "警告！", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                CGeneralMethods.SaveFormAction("日志信息", "您关闭了计算机！");
                Application.Exit();

                Thread.Sleep(500);

                Process.Start("shutdown.exe", "-s -t 1");
            }
        }

        private void btn_最小化_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }

        private void button_最大化_Click(object sender, EventArgs e)
        {
            Location = new Point(0, 0);
        }

        private void btn_退出_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(new Form { TopMost = true }, "确认退出软件？", "警告！", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                CGeneralMethods.SaveFormAction("日志信息", "您退出了软件！");
                Application.Exit();
            }
        }
        #endregion

        #region 控件
        private void button_启动_Click(object sender, EventArgs e)
        {
            try
            {
                int aaa = int.Parse(CINIOperationClass.GetSetting("JR", "OK", "100", "C:\\Windows\\SysIni.ini"));
                if (aaa != 0)
                {
                    MessageBox.Show(new Form { TopMost = true }, "请联系厂家：18876306809！");
                    return;
                }
                if (!b_数据比对 )
                {
                    MessageBox.Show(new Form { TopMost = true }, "名称数据比对不成功，请检查激光文件！");
                    return;
                }
                if (red)
                {
                    MessageBox.Show(new Form { TopMost = true }, "请先关闭红光预览！");
                    return;
                }
                b_生产中 = true;
            }
            catch (Exception)
            {
                MessageBox.Show(new Form { TopMost = true }, "请联系厂家：18876306809！");
            }
          
        }
        private void button_停止_Click(object sender, EventArgs e)
        {
            b_生产中 = false;
        }

        private void Button_激光加载_Click(object sender, EventArgs e)
        {
            try
            {
                LaserFileName = lb_Show_Mes.SelectedItem.ToString();
                LaserIniPath = LaserPath + "\\" + lb_Show_Mes.SelectedItem.ToString() + ".ezd";
                OpenLaserType();
                CINIOperationClass.INIWriteValue(Ini_SysPath, "位置信息", "激光文件位置", LaserIniPath);
                CINIOperationClass.INIWriteValue(Ini_SysPath, "位置信息", "激光文件名称", LaserFileName);
                CGeneralMethods.SaveFormAction("日志信息", "*加载了雕刻文件，地址：" + LaserIniPath);

                string temp = "切换机型为：" + LaserIniPath + "     当前时间：" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
                TypeData.Add(temp);

                DataName = LaserFileName;

                int_当前型号加工数量 = 0;
                b_生产中 = false;
            }
            catch (Exception)
            {
                MessageBox.Show(new Form { TopMost = true }, "切换异常！");
            }


        }

        private void btn_Ezd编辑_Click(object sender, EventArgs e)
        {
            JczLmc.Close();
            ShowEzCad();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            JczLmc.Initialize(Application.StartupPath, false);
        }

        private void button_查看日志信息_Click(object sender, EventArgs e)
        {
            try
            {
                string[] temp = File.ReadAllLines(DataPath, Encoding.Default);
                Frm_生产日志信息 frm_ = new Frm_生产日志信息(temp);
                frm_.Show();
            }
            catch (Exception er)
            {
                MessageBox.Show(new Form { TopMost = true }, er.Message);
            }
        }

        private void panel_菜单栏_MouseDown(object sender, MouseEventArgs e)
        {
            GeneralAPI.CGeneralMethods.ReleaseCapture();
            GeneralAPI.CGeneralMethods.SendMessage(this.Handle, GeneralAPI.CGeneralMethods.WM_SYSCOMMAND, GeneralAPI.CGeneralMethods.SC_MOVE + GeneralAPI.CGeneralMethods.HTCAPTION, 0);
        }

        Stopwatch stopwatch = new Stopwatch();
       
        private void textBox搜索_TextChanged(object sender, EventArgs e)
        {
            stopwatch.Restart();
         
                Director();
           
        }


        #endregion

        private const int ITEM_PADDING = 13;//各项之间的边距
        private void lb_Show_Mes_DrawItem(object sender, DrawItemEventArgs e)
        {
            int index = e.Index;//获取当前要进行绘制的行的序号，从0开始。
            if (index < 0)
            {
                return;
            }

            ListBox listBox = sender as ListBox;

            e.DrawBackground();//画背景颜色

            e.DrawFocusRectangle();//画聚焦项的边框

            Graphics g = e.Graphics;//获取Graphics对象。

            Rectangle itemBounds = e.Bounds;//获取当前要绘制的行的一个矩形范围。

            //文字绘制的区域，留出一定间隔

            Rectangle textBounds = new Rectangle(itemBounds.X, itemBounds.Y + ITEM_PADDING, itemBounds.Width, itemBounds.Height);

            string text = Convert.ToString(listBox.Items[index]);

            //因为文本可能会非常长，因此要用自绘实现ListBox项目的自动换行

            TextRenderer.DrawText(g, text, e.Font, textBounds, e.ForeColor,

               TextFormatFlags.WordBreak);

            g.DrawRectangle(Pens.BlueViolet, itemBounds);//画每一项的边框，这样清楚分出来各项。  
        }

        private void lb_Show_Mes_MeasureItem(object sender, MeasureItemEventArgs e)
        {
            ListBox listBox = sender as ListBox;

            int index = e.Index;//获取当前要进行绘制的行的序号，从0开始。

            if (index < 0)
            {
                return;
            }
            string text = Convert.ToString(listBox.Items[index]);

            //超范围后自动换行

            System.Drawing.Size size = TextRenderer.MeasureText(text, listBox.Font, listBox.Size, TextFormatFlags.WordBreak);

            e.ItemWidth = size.Width;

            e.ItemHeight = size.Height + ITEM_PADDING * 2;//适当多一点高度，避免太挤
        }

        private void Button_手动打标_Click(object sender, EventArgs e)
        {
            try
            {
                int aaa = int.Parse(CINIOperationClass.GetSetting("JR", "OK", "100", "C:\\Windows\\SysIni.ini"));
                if (aaa != 0)
                {
                    MessageBox.Show(new Form { TopMost = true }, "请联系厂家：18876306809！");
                    return;
                }
              
            }
            catch (Exception)
            {
                MessageBox.Show(new Form { TopMost = true }, "请联系厂家：18876306809！");
            }
            Mark();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        bool red = false;
        private void Button_红光预览_Click(object sender, EventArgs e)
        {
            red = !red;
        }

        private void button_清空计数_Click(object sender, EventArgs e)
        {
            DataName = DataName + " 同机型新的一盘计数";
            int_当前型号加工数量 = 0;
            CINIOperationClass.INIWriteValue(DataPath, "不同机型加工计数", DataName, int_当前型号加工数量.ToString());

            string temp = "您清空了计数，同款型号开始新的技术，新的型号名称为：" + DataName + "     当前时间：" + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
            TypeData.Add(temp);
        }
    }
}
